const fs = require("fs");
const path = require("path");

exports.run = async(client, message, args) => {

    if(!args[0]) return client.createMessage(message.channel.id, "⚠️ No role ID was provided.");

    const targetRole = message.channel.guild.roles.get(args[0]);

    if(!targetRole) return client.createMessage(message.channel.id, "⚠️ Specified role ID does not exist.");

    const outputDir = path.join(__dirname, "..", "output")
    const outputJSONDir = path.join(outputDir, "output.json"); // The directory where the produced JSON file will be saved.
    var membersWithRole;

    await message.channel.guild.fetchMembers().then(ml => {

        membersWithRole = ml.filter(m => m.roles.includes(args[0]));

    }).catch(e => {

        console.error(e.stack);

        membersWithRole = false;

    });

    if(membersWithRole === false) return errNoti();

    var membersArray = [];

    for(m of membersWithRole){
        membersArray.push(m.id);
    }

    // Check if the output directory exists. If it doesn't exist, create it.
    if(!fs.existsSync(outputDir)){

        fs.mkdir(outputDir, e => {

           if(e){
                console.error(e.stack);
                errNoti();
           }

        });

    }

    fs.access(outputJSONDir, fs.constants.F_OK, e => {

        if(e){
            var jsonObj = {};

            jsonObj[args[0]] = membersArray;

            // If the output file does not exist, write the JSON to a new file.
            fs.writeFile(outputJSONDir, JSON.stringify(jsonObj), e => {
                if(e){
                    console.error(e.stack);
                    errNoti();
                }
                else{
                    client.createMessage(message.channel.id, `Successfully saved user IDs of all members with the role ${args[0]} to a new output file.`);
                }
            });
        }
        else{
           /* If the output file already exists, append the JSON string to the existing file.
            * This is notably slower than simply writing to a new JSON file as it has to read the file, then convert that to a string.
            */

            fs.readFile(outputJSONDir, "utf8", (e, d) => {

                if(e){
                    console.error(e.stack);
                    client.createMessage(message.channel.id, "⚠️ Failed to parse contents of JSON file.");
                }
                else{
                    var jsonParsed;

                    jsonParsed = JSON.parse(d);

                    jsonParsed[args[0]] = membersArray; // Overwrite the members array for that role ID.

                    fs.writeFile(outputJSONDir, JSON.stringify(jsonParsed), e => {
                        if(e){
                            console.error(e.stack);
                            errNoti();
                        }
                        else{
                            client.createMessage(message.channel.id, `Successfully appended user IDs of all members with the role ${args[0]} to the output file.`);
                        }
                    });
                }
            });
        }

    });

    function errNoti(){
        // A basic function for notifying the person who ran the command.
        client.createMessage(message.channel.id, "⚠️ An error occurred when attempting to write into the JSON file.");
    }

}

